package org.n3r.idworker.utils;

import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @Author wyw
 * @Description IP工具类
 * @Date 2022/2/23 16:41
 * @Version 1.0
 */
@Component
public class IpUtil {

    /**
     * @Description: TODO
     * @Date: 2022/2/23 16:56
     **/
    public static String getRequestIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        final String unknown = "unknown";
        try {
            // url经代理时，x-forward-for值为 ip,proxy1,proxy2。Proxy-Client-Ip为apache代理添加头信息，WL-Proxy-Client-Ip 为weblogic添加头信息
            ipAddress = request.getHeader("x-forward-for");
            if (ipAddress == null || ipAddress.length() == 0 || unknown.equals(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-Ip");
            }
            if (ipAddress == null || ipAddress.length() == 0 || unknown.equals(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-Ip");
            }
            if (ipAddress == null || ipAddress.length() == 0 || unknown.equals(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if ("127.0.0.1".equals(ipAddress)) {
                    InetAddress inetAddress = null;
                    try {
                        inetAddress = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = inetAddress.getHostAddress();
                }
            }
            // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割。 // "***.***.***.***".length()
            if (ipAddress != null && ipAddress.length() > 15) {
                if(ipAddress.indexOf(",")>0){
                    ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
                }
            }

        } catch (Exception e) {
            ipAddress = "";
        }
        return ipAddress;
    }
}
